<template>
  <rm-layout-top splitcolor="white" :splitwidth=5 :fixsize=40 :canDrag=false>
    <template v-slot:fix>
      <div style="height:40px;border:1px solid #CCC">
        <div class="search-title">
          <table style="width:100%">
            <tr>
              <td>菜单</td>
              <td>
                <el-select v-model="searchobj.prgcode" filterable clearable @keyup.enter.native="selectBlur()"
                  ref="ddlprgcodeSelect">
                  <el-option v-for="(item, index) in prgcodeOption" :key="index" :label="item.label" :value="item.value">
                    <span style="float: left">{{ item.label }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                  </el-option>
                </el-select>
              </td>
              <td>类别</td>
              <td>
                <el-select v-model="searchobj.reportkind" filterable clearable @change="reportkindChange">
                  <el-option v-for="(item, index) in reportkindOption" :key="index" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </td>
              <td>快速检索</td>
              <td>
                <el-input v-model="searchobj.reportname" placeholder="统计报表ID或名称" @keyup.enter.native="InitPage" clearable>
                </el-input>
              </td>

            </tr>
          </table>
        </div>
        <div class="top-deal">
          <el-button @click.native="btnQuery" icon="el-icon-search" type="primary">查询</el-button>
          <el-button icon="el-icon-menu" @click.native="btnPreCond">预设条件</el-button>
          <el-button icon="el-icon-s-tools" @click="btnSetStyle">样式设置</el-button>
        </div>
      </div>
    </template>
    <rm-layout-right splitcolor="white" movingcolor="#CCFFFF" :splitwidth=5 :fixsize=400>
      <template v-slot:fix>
        <div style="height:100%;border:1px solid #ccc;text-align:center;">
          <div style="height:30px;padding:10px;font-weight:bold">{{ ReportnameTitle }}</div>
          <div style="height:calc(100%-30px);">
            <el-image style="width: 100%; height: 100%" :src="ImageUrl" :fit="ReportnameTitle"
              @dblclick="LookOverImg"></el-image>
          </div>
        </div>
      </template>
      <div style="height:100%;width:100%;">
        <vxe-table :data.sync="DC_StatReportData" :loading="left_loading" :select-config="{ reserve: true }"
          :sort-config="{ trigger: 'cell' }" border height="auto" highlight-current-row highlight-hover-column
          highlight-hover-row how-header-overflow ref="xTable" resizable show-overflow size="mini" stripe
          @current-change="currentChangeEvent" @cell-dblclick="DblclickOpen">
          <vxe-table-column field="chkflag" title="启用" width="50" align="center">
            <template v-slot="{ row }">
              <el-checkbox v-model="row.chkflag" true-label="1" false-label="0"
                @change="chkflagChange(row)"></el-checkbox>
            </template>
          </vxe-table-column>
          <vxe-table-column field="reportkind" title="报表类别" width="80" header-align="center"></vxe-table-column>
          <vxe-table-column field="reportname" title="报表名称" width="140" header-align="center"></vxe-table-column>
          <vxe-table-column field="prgcode" title="所属菜单" width="80" header-align="center"
            align="center"></vxe-table-column>
          <vxe-table-column field="reportsql" title="统计SQL(双击查看)" width="200" header-align="center"></vxe-table-column>
          <vxe-table-column field="description" title="报表说明(双击查看)" width="117" header-align="center"></vxe-table-column>
          <vxe-table-column field="prestat" title="是否预统计" width="80" header-align="center" align="center">
            <template v-slot="{ row }">
              <el-checkbox v-model="row.prestat" true-label="1" false-label="0" disabled></el-checkbox>
            </template>
          </vxe-table-column>
          <vxe-table-column field="prestattable" title="预统计表名" width="90" header-align="center"></vxe-table-column>
          <vxe-table-column field="prestatsql" title="预统计SQL(双击查看)" width="120" header-align="center"></vxe-table-column>
          <vxe-table-column field="startstatdate" title="开始统计日期" width="90" header-align="center"
            align="right"></vxe-table-column>
          <vxe-table-column field="laststatdate" title="最后统计日期" width="90" header-align="center"></vxe-table-column>
          <vxe-table-column field="seq" title="序号" width="50" header-align="center"></vxe-table-column>
          <vxe-table-column field="statreportid" title="统计报表ID" width="79" header-align="center"></vxe-table-column>
        </vxe-table>
      </div>
    </rm-layout-right>
    <!--放大-->
    <el-dialog :visible.sync="dialogImgVisible" v-el-drag-dialog :close-on-click-modal="false" :title="ReportnameTitle">
      <img width="100%" :src="ImageUrl" alt="">
    </el-dialog>

    <!--预设条件-->
    <el-dialog :visible.sync="diagPreCond" v-el-drag-dialog :close-on-click-modal="false" title="预设条件" width="500px">
      <div style="overflow:auto;text-align:center" v-if="preCondData.length > 0">
        <table style="width:100%">
          <tr v-for="(item, index) in preCondData" :key="index">
            <td>{{ item.colname }}</td>
            <td style="color:red">=</td>
            <td>
              <!--1 checkbox-->
              <div v-if="item.valuetype == '1'">
                <el-checkbox true-label="1" false-label="0" v-model="item.defaultvalue"></el-checkbox>
              </div>
              <!--2 input-->
              <div v-else-if="item.valuetype == '2'">
                <el-input v-model="item.defaultvalue"></el-input>
              </div>
              <!--3 valuelist-->
              <div v-else-if="item.valuetype == '3'">
                <el-select v-model="item.defaultvalue" filterable style="width:158px">
                  <el-option v-for="sitem in item.valuelist.split('|')" :key="sitem.split(' ')[0]"
                    :label="item.substring(item.indexOf(' '))" :value="item.split(' ')[0]">
                  </el-option>
                </el-select>
              </div>
              <!--4 列表多选-->
              <div v-else-if="item.valuetype == '4'">
                <el-input v-model="item.defaultvalue" ref="refMutipleSelect" :key="1" placeholder="列表多选双击开窗" readonly
                  @dblclick.native="DialogMutipleSelect(item.valuelist, item.defaultvalue, item.colname, item.colcode, item.statreportid)">
                  <el-button slot="append">选择</el-button>
                </el-input>
              </div>
              <!--5 SQL-->
              <div v-else-if="item.valuetype == '5'">
                <rm_ddl_SqlSingle :sql="item.valuelist" :key="item.colcode" v-model="item.defaultvalue" ref="refSqlSingle"
                  width="100%" :showselect="false" @change="SqlSingleChange"
                  :keyid="item.colcode + '$' + item.statreportid">
                </rm_ddl_SqlSingle>
              </div>
              <!--6 SQL多选-->
              <div v-else-if="item.valuetype == '6'">
                <el-input v-model="item.defaultvaluename" ref="refSql" :key="item.colcode" placeholder="SQL多选双击开窗"
                  readonly
                  @dblclick.native="DialogSql(item.valuelist, item.defaultvalue, item.colname, item.colcode, item.statreportid)">
                  <el-button slot="append"
                    @click.native="DialogSql(item.valuelist, item.defaultvalue, item.colname, item.colcode, item.statreportid)">选择</el-button>
                </el-input>
              </div>
              <!--6 时间区间-->
              <div v-else-if="item.valuetype == '9'">
                <el-date-picker v-model="item.defaultvalue[0]" :type="item.dateformat == '1' ? 'daretime' : 'date'"
                  placeholder="选择日期" :value-format="item.dateformat == '1' ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd'"
                  style="width:130px"></el-date-picker>-
                <el-date-picker v-model="item.defaultvalue[1]" :type="item.dateformat == '1' ? 'daretime' : 'date'"
                  placeholder="选择日期" :value-format="item.dateformat == '1' ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd'"
                  style="width:130px">
                </el-date-picker>
              </div>
            </td>
          </tr>
        </table>
      </div>
      <div v-else>没有获取到预设条件！</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="SaveRecord">确 定</el-button>
        <el-button @click="diagPreCond = false, SaveRecordTypetype = '1'">取 消</el-button>
      </span>
    </el-dialog>

    <!--多选弹窗--->
    <el-dialog width="900px" v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" :title="multichktitle"
      :visible.sync="dialogMultipleVisible" :destroy-on-close="true">
      <rm-SqlMultiple :leftOption="LeftListOptions" :rightOption="RightListOptions" :name="fieldname"
        @change="closedialog"></rm-SqlMultiple>
    </el-dialog>

    <!--双击查看内容-->
    <el-dialog :title="RecTitle" :visible.sync="dialogmsg" width="50%" v-el-drag-dialog :append-to-body="true"
      :close-on-click-modal="false">
      <div style="width:100%;height:380px;overflow:auto;border:3px double #ccc;padding:10px">
        {{ RecContents }}
      </div>
    </el-dialog>
  </rm-layout-top>
</template>

<script type="text/javascript">
import XEUtils from "xe-utils";
export default {
  name: "MNG122",
  data() {
    return {
      prgcodeOption: [],
      reportkindOption: [],
      preCondData: [],
      OldPreCondData: [],
      searchobj: { prgcode: "", reportname: "" },
      DC_StatReportData: [],
      dialogMultipleVisible: false,
      ImageUrl: "",
      ReportnameTitle: "",
      left_loading: false,
      right_loading: false,
      dialogImgVisible: false,
      diagPreCond: false,
      dialogmsg: false,
      LeftListOptions: [],
      RightListOptions: [],
      fieldname: "",
      multichktitle: "",
      RecContents: "",
      RecTitle: "",
      userno: this.$tool.getSession(this.$tool.loginuserno),
      SaveRecordType: "1"
    };
  },
  created() {
    this.initOption(); //初始化下拉框的数据
    this.InitPage(); //初始化主列表
  },
  methods: {
    initOption() {
      this.$tool
        .request({
          url: "MNG/MNG1/MNG122",
          method: "post",
          data: {
            action: "initOption"
          }
        })
        .then(res => {
          this.prgcodeOption = res.prgcodeOption;
          this.reportkindOption = res.reportkindOption;
        })
        .catch(e => {
          this.$alert(e, "error");
        });
    },
    btnQuery() {
      this.InitPage();
    },
    InitPage() {
      this.left_loading = true;
      this.$tool
        .request({
          url: "MNG/MNG1/MNG122",
          method: "post",
          data: {
            action: "InitPage",
            ...this.searchobj
          }
        })
        .then(res => {
          this.DC_StatReportData = res.Data;
          if (res.Data.length > 0) {
            this.$refs.xTable.setCurrentRow(res.Data[0]);
            this.queryRight(res.Data[0]);
          } else {
            this.$refs.xTable.setCurrentRow(null);
            this.ReportnameTitle = "";
            this.rptstylelist = {};
            this.selrow = [];
            this.preCondData = [];
            this.OldPreCondData = [];
            this.ImageUrl = "";
          }
          this.left_loading = false;
        })
        .catch(e => {
          this.left_loading = false;
          this.$alert(e);
        });
    },
    queryRight(row) {
      this.statreportid = row.statreportid;
      this.ReportnameTitle = row.reportname;
      this.right_loading = true;
      this.$tool
        .request({
          url: "MNG/MNG1/MNG122",
          method: "post",
          data: {
            action: "queryRight",
            statreportid: row.statreportid
          }
        })
        .then(res => {
          this.preCondData = res.preCondData.filter(m => m.colname != "@date");
          this.OldPreCondData = XEUtils.clone(res.preCondData, true);
          this.ImageUrl = res.SampleGraph;
          this.right_loading = false;
        })
        .catch(e => {
          this.right_loading = false;
          this.$alert(e);
        });
    }, //列表多选
    DialogMutipleSelect(data, chkdata, name, code, id) {
      this.fieldname = code;
      this.multichktitle = name;
      this.statreportid = id;
      let dataValue = data.split("|");
      this.RightListOptions = [];
      this.LeftListOptions = [];
      this.ListTableColumn = [{ field: "data", title: "代码", width: 120 }, { field: "display", title: "名称", width: 160 }];
      let thisvalue = chkdata.split(",");
      if (thisvalue.length > 0) {
        thisvalue.forEach(item => {
          dataValue.forEach(element => {
            var kvalue = element.split(" ");
            if (kvalue[0] == item) {
              this.RightListOptions.push({
                display: kvalue[1],
                data: kvalue[0]
              });
            }
          });
        });
      }
      if (dataValue.length > 0) {
        dataValue.forEach(element => {
          var kvalue = element.split(" ");
          if (thisvalue.indexOf(kvalue[0]) < 0) {
            this.LeftListOptions.push({
              display: kvalue[1],
              data: kvalue[0]
            });
          }
        });
      }
      this.dialogMultipleVisible = true;
    },
    //sql多选弹窗
    DialogSql(sql, chkdata, name, code, id) {
      this.$tool
        .request({
          url: "MNG/MNG1/MNG122",
          method: "post",
          data: {
            action: "SqlInitialList",
            sql: sql,
            chkdata: chkdata
          }
        })
        .then(res => {
          this.LeftListOptions = res.LeftGrid;
          this.RightListOptions = res.RightGrid;
          this.fieldname = code;
          this.multichktitle = name;
          this.statreportid = id;
          this.dialogMultipleVisible = true;
        })
        .catch(e => {
          this.$alert(e, "error");
        });
    },
    //多选弹窗关闭
    closedialog(value, code, valuename) {
      if (value != "close") {
        this.SetValue(code, this.statreportid, value, valuename, "duo"); //多选
      }
      this.dialogMultipleVisible = false;
    }, //单选赋值
    SqlSingleChange(value, idcode) {
      let code = idcode.split("$")[0];
      let id = idcode.split("$")[1];
      this.SetValue(code, id, value, "", "dan"); //单选
    }, //赋值函数
    SetValue(code, id, value, valuename, type) {
      let data = this.preCondData.find(m => m.colcode == code && m.statreportid == id);
      if (!!data) {
        if (type == "duo") {
          data.defaultvalue = value;
          data.defaultvaluename = valuename;
        } else {
          data.defaultvalue = value;
          //data.defaultvaluename = valuename;
        }
      } else {
        this.$alert("请刷新重试", "出错");
      }
    },
    //主列表单选保存
    chkflagChange(row) {
      if (row.chkflag == "1" && this.preCondData.length > 0) {
        row.chkflag = "0";
        this.SaveRecordTypetype = "2";
        this.diagPreCond = true;
      } else {
        row.chkflag = "1";
        this.chkflagInuse(row);
      }
    },
    //报表启用
    chkflagInuse(row) {
      if (!row) row = this.$refs.xTable.getCurrentRow();
      var chkflag = XEUtils.clone(row.chkflag, true);
      if (chkflag == "1") chkflag = "0";
      else chkflag = "1";
      let chkstr = chkflag + "|" + row.statreportid + "|" + row.reportname;
      this.$tool
        .request({
          url: "MNG/MNG1/MNG122",
          method: "post",
          data: {
            action: "chkflagChange",
            chkstr: chkstr
          }
        })
        .then(res => {
          if (res.errcode == "1") {
            this.$pub.message(this, "保存成功！", "success");
            if (this.SaveRecordTypetype == "2") {
              this.SaveRecordTypetype = "1";
            }
            row.chkflag = chkflag;
            this.diagPreCond = false;
          } else {
            this.$alert("保存失败！" + res.errmsg, "失败");
          }
        })
        .catch(e => {
          this.$alert(e);
        });
    },
    //行切换
    currentChangeEvent({ row, column }) {
      this.queryRight(row);
    },
    //预设条件
    btnPreCond() {
      this.diagPreCond = true;
      this.this.SaveRecordTypetype = "1";
    },
    //预设条件保存
    SaveRecord() {
      if (this.preCondData.length > 0) {
        this.$tool
          .request({
            url: "MNG/MNG1/MNG122",
            method: "post",
            data: {
              action: "SaveRecord",
              saveinfo: this.preCondData,
              oldinfo: this.OldPreCondData
            }
          })
          .then(res => {
            if (res.errcode == "1") {
              if (this.SaveRecordTypetype == "2") this.chkflagInuse();
              else {
                this.$pub.message(this, "保存成功！", "success");
                this.SaveRecordTypetype = "1";
                this.diagPreCond = false;
              }
            } else {
              this.$alert("保存失败！" + res.errmsg, "失败");
            }
          })
          .catch(e => {
            this.$alert(e);
          });
      } else {
        this.diagPreCond = false;
        this.SaveRecordTypetype = "1";
      }
    },
    LookOverImg() {
      this.dialogImgVisible = true;
    }, //下拉回车
    selectBlur() {
      let query = this.$refs.ddlprgcodeSelect.selectedLabel;
      var re = /^[a-zA-Z]+.?[0-9]*$/;
      if (!re.test(query)) {
        //不是数字,暂时不做任何事
      } else {
        //是LIS640这种形式
        if (query !== "") {
          let data = this.prgcodeOption.find(m => m.value.toUpperCase() == query.toUpperCase());
          if (!!data) {
            this.searchobj.prgcode = data.value;
          } else {
            this.searchobj.prgcode = query;
          }

          this.$refs.ddlprgcodeSelect.blur();
        }
      }
    }, //双击查看
    DblclickOpen({ row, column }) {
      if (["reportsql", "description", "prestatsql"].includes(column.property)) {
        this.RecTitle = column.title.split("(")[0];
        this.RecContents = row[column.property];
        this.dialogmsg = true;
      }
    }, //样式设置
    btnSetStyle() {
      if (typeof jsObj != "undefined") {
        if (this.statreportid == "") {
          this.$alert("没有获取到统计报表ID");
          return false;
        }
        this.$tool
          .request({
            url: "MNG/MNG1/MNG122",
            method: "post",
            data: {
              action: "adjustifyStatStyle",
              statreportid: this.statreportid
            }
          })
          .then(res => {
            if (res.errcode == "1") {
              if (res.data.length > 0) {
                let str = JSON.stringify(res.columns);
                str += "\r";
                str += JSON.stringify(res.data);
                let sql = btoa(encodeURIComponent(str));
                jsObj.SetCustomJsonPrintConfig(this.statreportid + "", sql, this.userno, "HIV统计样式");
              } else {
                this.$alert("获取数据失败！", "提示");
              }
            } else {
              this.$alert("数据读取失败！" + res.errmsg, "提示");
            }
          })
          .catch(e => {
            this.$alert(e);
          });
      } else {
        this.$alert("请使用" + this.$pub.clientname + "打开系统", "错误", {
          confirmButtonText: "确定"
        });
      }
    },
    reportkindChange(val) {
      this.InitPage();
    }
  }
};
</Script>

<style scoped>
table {
  font-size: 12px;
  border-collapse: separate;
  border-spacing: 5px;
  padding: 0px 2px 0px 5px;
}

.search-title {
  position: absolute;
}

.top-deal {
  right: 5px;
  position: absolute;
  top: 7px;
  display: flex;
  align-items: center;
}</style>
